// pages/noauth/noauth.js
var app = getApp();
Page({
  data: {
    show: false
  },
  onLoad: function(o) {
    this.toggle("show", !!o.noPhone);
  },
  toggle(type, val) {
    this.setData({
      [type]: val
    });
  },
  onClose: function() {
    this.toggle("show", false);
  },
  //登录
  getAuth: function(res) {
    var that = this;
    wx.login({
      fail: function(res) {
        wx.showToast({
          title: '登录失败',
          icon: 'none',
          duration: 2000
        })
      },
      success: function(res) {
        console.log(res);
        wx.setStorageSync('loginCode', res.code);
        that.saveUserInfo(res.code);
      }
    });

  },
  //解密手机号数据
  decryptPhone: function(data) {
    app.req({
      url: 'orgmini/user/deciphering',
      data: data,
      method: 'POST',
      success: function(res) {
        if (res.code === 200) {
          wx.navigateBack()
        } else {
          wx.showToast({
            title: res.msg,
            icon: 'none',
            duration: 2000
          })
        }
      }
    });
  },
  //需要用户点击，获取微信用户手机号
  getUserPhoneByWeChat: function(e) {
    console.log(e);
    var that = this;
    var detail = e.detail;
    var uid = wx.getStorageSync("uid");
    var data = {
      encryptedData: detail.encryptedData,
      ivdata: detail.iv,
      uid: uid
    }
    var code = wx.getStorageSync("loginCode");
    wx.checkSession({
      success() {
        data.code = code;
        that.decryptPhone(data);
      },
      fail() {
        wx.login({
          success: function(res) {
            wx.setStorageSync('loginCode', res.code);
            data.code = res.code;
            that.decryptPhone(data);
          }
        });
      }
    })

  },
  //查看用户是否有手机号
  getUserPhone: function() {
    var that = this;
    that.setData({
      show: true
    });
  },
  //保存用户信息
  saveUserInfo: function(userCode) {
    var that = this;
    wx.getUserInfo({
      lang: 'zh_CN',
      fail: function(res) {
        wx.showToast({
          title: '授权失败',
          icon: 'none',
          duration: 2000
        })
      },
      success: function(res) {
        app.req({
          url: 'orgmini/user/authorize',
          data: {
            encryptedData: res.encryptedData,
            iv: res.iv,
            code: userCode
          },
          method: 'POST',
          success: function(res) {
            if (res.code === 200) {
              wx.setStorageSync('uid', res.data.uid);
              that.getUserPhone();
            } else {
              wx.showToast({
                title: res.msg,
                icon: 'none',
                duration: 2000
              })
            }
          }
        });

      }
    });
  }
})